from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework import status

from .serializer import *


class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    @action(methods=['POST', 'DELETE'], detail=True)
    def article_op_tag(self, request, pk):
        article = self.get_object()
        data = request.data
        """
        {tag_id: 2}
        """
        tag_id = data['tag_id']
        tag = get_object_or_404(TagOfArticle, pk=tag_id)
        if request.method == 'POST':
            article.article_tags.add(tag)
        else:
            article.article_tags.remove(tag)
        serializer = ArticleSerializer(instance=article)
        return Response(serializer.data)


# Create your views here.
class TagOfArticleViewSet(ModelViewSet):
    def get_queryset(self):
        return TagOfArticle.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return TagOfArticleListSerializer
        else:
            return TagOfArticleDetailSerializer
